package services

import (
	"context"
	"log"
	"time"

	"demo2/server/agent"
	"demo2/server/storage"

	"github.com/google/uuid"
)

// ChatAgentService 基于Agent的聊天服务
type ChatAgentService struct {
	store *storage.RedisStore
	agent *agent.Agent
}

// NewChatAgentService 创建新的Agent聊天服务
func NewChatAgentService(store *storage.RedisStore, llmService *LLMService) *ChatAgentService {
	// 创建LLM服务包装器
	llmWrapper := NewLLMServiceWrapper(llmService)
	
	// 创建LLM适配器
	llmAdapter := agent.NewLLMAdapter(llmWrapper)

	// 配置Agent
	agentConfig := agent.AgentConfig{
		MaxMemorySize:    100,
		PlanningTimeout:  30 * time.Second,
		ExecutionTimeout: 60 * time.Second,
	}

	// 创建Agent
	agentInstance := agent.NewAgent(llmAdapter, store, agentConfig)

	return &ChatAgentService{
		store: store,
		agent: agentInstance,
	}
}

// Close 关闭服务
func (c *ChatAgentService) Close() error {
	return c.agent.Close()
}

// SendMessage 发送消息并获取回复
func (c *ChatAgentService) SendMessage(ctx context.Context, sessionID, userMessage string) (*storage.Message, error) {
	log.Printf("[CHAT-AGENT-SERVICE] 🤖 收到发送消息请求，会话ID: %s", sessionID)

	// 保存用户消息
	userMsg := &storage.Message{
		ID:        uuid.New().String(),
		SessionID: sessionID,
		Role:      "user",
		Content:   userMessage,
		Timestamp: time.Now(),
	}

	log.Printf("[CHAT-AGENT-SERVICE] 💾 保存用户消息到存储")
	if err := c.store.SaveMessage(ctx, userMsg); err != nil {
		log.Printf("[CHAT-AGENT-SERVICE] ❌ 保存用户消息失败: %v", err)
		return nil, err
	}

	// 使用Agent处理消息
	log.Printf("[CHAT-AGENT-SERVICE] 🤖 调用Agent处理消息...")
	agentResponse, err := c.agent.ProcessMessage(ctx, sessionID, userMessage)
	if err != nil {
		log.Printf("[CHAT-AGENT-SERVICE] ❌ Agent处理消息失败: %v", err)
		return nil, err
	}

	// 保存Agent回复
	aiMsg := &storage.Message{
		ID:        uuid.New().String(),
		SessionID: sessionID,
		Role:      "assistant",
		Content:   agentResponse.Content,
		Timestamp: agentResponse.Timestamp,
	}

	log.Printf("[CHAT-AGENT-SERVICE] 💾 保存Agent回复到存储")
	if err := c.store.SaveMessage(ctx, aiMsg); err != nil {
		log.Printf("[CHAT-AGENT-SERVICE] ❌ 保存Agent回复失败: %v", err)
		return nil, err
	}

	log.Printf("[CHAT-AGENT-SERVICE] ✅ 消息处理完成")
	return aiMsg, nil
}

// SendStreamMessage 发送消息并获取流式回复
func (c *ChatAgentService) SendStreamMessage(ctx context.Context, sessionID, userMessage string, responseChan chan<- string) error {
	log.Printf("[CHAT-AGENT-SERVICE] 🌊 收到流式消息请求，会话ID: %s", sessionID)

	// 保存用户消息
	userMsg := &storage.Message{
		ID:        uuid.New().String(),
		SessionID: sessionID,
		Role:      "user",
		Content:   userMessage,
		Timestamp: time.Now(),
	}

	if err := c.store.SaveMessage(ctx, userMsg); err != nil {
		log.Printf("[CHAT-AGENT-SERVICE] ❌ 保存用户消息失败: %v", err)
		return err
	}

	// 使用Agent处理流式消息
	log.Printf("[CHAT-AGENT-SERVICE] 🤖 调用Agent处理流式消息...")
	return c.agent.ProcessStreamMessage(ctx, sessionID, userMessage, responseChan)
}

// GetHistory 获取聊天历史
func (c *ChatAgentService) GetHistory(ctx context.Context, sessionID string) ([]*storage.Message, error) {
	return c.store.GetMessages(ctx, sessionID)
}

// ClearHistory 清除聊天历史
func (c *ChatAgentService) ClearHistory(ctx context.Context, sessionID string) error {
	// 清除存储中的历史
	if err := c.store.ClearMessages(ctx, sessionID); err != nil {
		return err
	}

	// 清除Agent记忆中的历史
	c.agent.GetMemory().ClearSession(sessionID)
	return nil
}

// GetAgentStats 获取Agent统计信息
func (c *ChatAgentService) GetAgentStats() map[string]interface{} {
	stats := make(map[string]interface{})
	
	// 获取记忆统计
	stats["memory"] = c.agent.GetMemory().GetMemoryStats()
	
	// 获取工具统计
	stats["tools"] = c.agent.GetTools().GetToolStats()
	
	return stats
}

// GetAvailableTools 获取可用工具列表
func (c *ChatAgentService) GetAvailableTools() []map[string]interface{} {
	return c.agent.GetTools().ListTools()
}
